// pages/map/getOrderNotGoing/getOrderNotGoing.js
const handler = require("../../../utils/function.js");
var img = handler.userImg;
var api = require("../../../api.js"),
  QQMapWX = require("../../../utils/qqmap-wx.js"),
    app = getApp();
var demo = new QQMapWX({
  key: 'VD2BZ-SUEK4-Y5OU7-XPL6G-K4AB5-BWBJN' // 必填
}); 
Page({
    /**
     * 页面的初始数据
     */
    data: {
        img: handler.userImg,
        polyline: [{
            points: [{
                longitude: 108.93,
                latitude: 32.28
            }, {
                longitude: 108.94,
                latitude: 32.27
            }],
            color: "#0299de",
            width: 9,
            dottedLine: false,
            arrowLine: true,
        }],
        controls: [{
            id: 1,
            iconPath: '../../../images/user/icon-22.png',
            position: {
                left: 10,
                top: 10,
                width: 50,
                height: 50
            },
            clickable: true
        }, {
            id: 2,
            iconPath: '../../../images/user/icon-30.png',
            position: {
                top: 240,
                left: 10,
                width: 50,
                height: 50
            },
            clickable: true
        }, ], //人物图片定位
        driver: wx.getStorageSync("serverDriver"),
        not_going_m: 0,
        not_going_s: 0,
        startAddress: null,
        myShow: true, //显示my的页面
        zuoyou: "icon-zuoyou", //my
        avatar: "../../../images/user/icon-07.png",
        buttonText: "登录",
        username: "未登录",
        orderGoing: false,
        homeHandlerShow: true,
        phone: "",
        order_no: '',
        is_service: 0,
        make: [
          {//用户位置:latitude+0.002
            iconPath: "../../../images/user/my-location.png",
            id: 0,
            latitude: 34.29418,
            longitude: 108.94712,
            width: 89,
            height: 25
          },
          {//司机位置
            iconPath: "../../../images/user/driver-img.png",
            id: 2,
            latitude: 34.30518,
            longitude: 108.94712,
            width: 20,
            height: 20
          },
          {
            iconPath: "../../../images/user/icon-07.png",
            id: 3,
            latitude: 23.099994,
            longitude: 113.324520,
            width: 50,
            height: 50
          },
        ],
        drivername: '',
        ordernum: 0,
        graded: 0,
        avatar_url: '',
        been_driving: 0,
        work_phone: 0,
        left_width: 750,
        distance:'',
    },
    regionchange(e) {
        console.log(e.type)
    },
    markertap(e) {
        console.log(e.markerId)
    },
    // 地图图片点击事件
    controltap(e) {
        console.log("map controltap", e.controlId)
        if (e.controlId === 1) {
            this.openMyPageHandler();
        } else {
            const addresses = handler.getLatLntHandler((res) => {
                //  console.log("一键定位",res);
                this.setData({
                    startAddress: res.startAddress, //开始位置
                })
            });
        }
    },
    // openMyPageHandler 打开我的页面
    openMyPageHandler: function() {
        const {
            pageRight,
            myShow
        } = this.data;
        console.log("openMyPageHandler", pageRight, myShow);
        if (myShow) {
            this.setData({
                pageRight: 620,
                left_width:130,
                myShow: !myShow,
                controls: [{
                    id: 1,
                    iconPath: '../../../images/user/icon-33.png',
                    position: {
                        top: 144,
                        left: 10,
                        width: 41,
                        height: 41
                    },
                    clickable: true
                }]
            });
        } else {
            this.setData({
                pageRight: 0,
                left_width: 750,
                myShow: !myShow,
                controls: [{
                    id: 1,
                    iconPath: '../../../images/user/icon-22.png',
                    position: {
                        left: 10,
                        top: 10,
                        width: 50,
                        height: 50
                    },
                    clickable: true
                }, {
                    id: 2,
                    iconPath: '../../../images/user/icon-30.png',
                    position: {
                        top: 240,
                        left: 10,
                        width: 50,
                        height: 50
                    },
                    clickable: true
                }, ],
            });
          this.changeIcon()
            
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            order_no: options.order_no
        })
        /*var time = setInterval(() => {
            if (that.data.not_going_s === 5 && that.data.not_going_m === 0) {
                clearInterval(time);
            } else {
                that.timeTask();
            }
        }, 1000);*/
    },
  // 获取位置路线
  getPolyline: function (start,end) {
    //添加临时地址
    wx.setStorageSync("endAddress", 
    { "title": "陕西省西安市未央区龙首北路西段1号",
     "address": "陕西省西安市未央区龙首北路西段1号", 
      "location": { "lat": 34.30518, "lng": 108.94712 } } )
    handler.getPolyline((res) => {
    
      if (res) {
        const polyline = this.data.polyline;
        polyline[0].points = res;
        this.setData({
          polyline
        });
      }
    })
  },
    // callPhoneHandler  打电话功能
    callDriverPhoneHandler: function() {
        handler.callPhoneHandler(this.data.work_phone)
    },
    // callServerPhoneHandler 打客服电话号码
    callServerPhoneHandler: function(e) {
        console.log(e.currentTarget.dataset.phone)
      handler.callPhoneHandler(e.currentTarget.dataset.phone)
    },
    // deleteOrderHandler 删除订单功能 cancel_order
    deleteOrderHandler: function() {
        var that = this;
        app.request({
            url: api.order.cancel_order,
            method: 'post',
            data: {
                order_no: that.data.order_no,
            },
            success: function(rs) {
                // console.log('代驾人员正在赶来ss', rs)
                if (rs.code == 1) {
                    wx.showToast({
                        title: '订单取消已成功',
                    })
                    clearInterval(this.timeTask)
                  
                    wx.redirectTo({
                        url: '../driverServer/driverServer',
                    })
                }else{
                     wx.showToast({
                        title:rs.msg,
                    })
                }
            }
        })
      
    },
    // timeTask 时间业务
    timeTask: function() {
        var not_going_s = this.data.not_going_s;
        var not_going_m = this.data.not_going_m;
        not_going_s++;
        if (not_going_s > 59) {
            not_going_s = 0;
            not_going_m++;
        }
        this.setData({
            not_going_s,
            not_going_m
        });
       
    },
    // orderGoingHandler 订单进行中事件
    orderGoingHandler: function() {
        wx.showToast({
            title: '目前还没有正在进行中的订单',
            icon: "none"
        })
        this.setData({
            orderGoing: false
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
         if (wx.getStorageSync("userMessage") !== "") {
            this.setData({
                avatar: wx.getStorageSync("userMessage").avatar,
                username: wx.getStorageSync("userMessage").username,
                buttonText: wx.getStorageSync("userMessage").buttonText,
                phone: wx.getStorageSync("phonep"),
            });
        }
        var that = this;
        const time = setInterval(() => {
            if (that.data.is_service == 2) {
                clearInterval(time);
                wx.redirectTo({
                    url: '../orderGoing/orderGoing?order_no=' + that.data.order_no,
                })
            } else if(that.data.is_service == 1){
                 clearInterval(time);
                wx.redirectTo({
                    url: '../orderGoing/orderGoing?order_no=' + that.data.order_no,
                })
            }else{
                that.postionTask();
            }
        }, 2000);
      handler.getLatLntHandler(res => {
        console.log(res, 'res11111111111111')
        that.setData({
          startAddress: res.startAddress, //开始位置
        })
      })
        // 按钮重定位
      this.changeIcon()
      //路线规划
      this.getPolyline()
    },
  // 获取距离
  get_distance: function (start, target, callback) {
    demo.calculateDistance({
      from: {
        latitude: start.location.lat,
        longitude: start.location.lng
      },
      to: [{
        latitude: target.location.lat,
        longitude: target.location.lng
      }],
      success: function (res) {
        console.log(res.result.elements[0].distance);
        callback({ distance: res.result })
      },
      fail: function (res) {
        // console.log(res);
        // console.log("*****************************")
        callback(res)
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
    /*
     * 定时获取订单状态及代驾人员位置
     */
    postionTask: function() {
        var that = this;
        app.request({
            url: api.order.waiting,
            method: 'post',
            data: {
                order_no: that.data.order_no,
            },
            success: function(rs) {
              console.log('代驾人员正在赶来ss', rs)
              //  debugger
                // console.log('代驾人员正在赶来ss', rs)
                if (rs.code == 1) {
                    wx.setStorageSync("startAddress",rs.data.startAddress);
                    wx.setStorageSync("endAddress",rs.data.endAddress);
                    that.getPolyline();
                    
                    that.setData({
                        startAddress: rs.data.lang,
                        // make: rs.data.start_location,
                        is_service: rs.data.is_service,
                        drivername: rs.data.userinfo.real_name,
                        ordernum: rs.data.userinfo.ordernum,
                        graded: rs.data.userinfo.graded,
                        avatar_url: rs.data.userinfo.avatar_url,
                        been_driving: rs.data.userinfo.been_driving,
                        work_phone: rs.data.userinfo.work_phone,
                        signature: rs.data.userinfo.signature,
                        distance: rs.data.distance,
                        serverphone: rs.data.serverphone,
                    })                
                    }
              // that.get_distance(rs.data.startAddress, rs.data.endAddress,res=>{
              //   console.log(res,'11111111111111111')
              // })
              console.log(rs.data.start_location,'22222222222222');
            }
        })
    },
    // 用户信息事件
    /**loginHandler用户登录页面 */
    loginHandler: function(e) {
        if (this.data.buttonText === "登录") {
            handler.loginHandler((res) => {
                // console.log("用户信息事件",res);
                this.setData({
                    res,
                });
                const that = this;
                wx.showModal({
                    title: '获取手机号码',
                    content: '我们需要获取你的电话号码，一边与和你保持实时的联系，防止你的订单丢失',
                    success: function(res) {
                        if (res.confirm) {
                          wx.reLaunch({
                            url: '../../user/getPhone/getPhone'
                          })
                        //   wx.wx.reLaunch({url:})
                        //     handler.intoPageHandler("../../user/getPhone/getPhone");
                         }
                    },
                    fail: function() {
                        wx.showToast({
                            title: '登录失败',
                            icon: "none"
                        })
                    }
                })
            })
        } else {
            this.setData({
                avatar: "../../../images/user/icon-07.png",
                username: "未登录",
                buttonText: "登录",
                phone: ""
            });
        }
    },
    // intoPageHandler 页面跳转
    intoPageHandler: function(e) {
        // console.log(e.currentTarget.dataset.skip);
        
        handler.intoPageHandler(e.currentTarget.dataset.skip)
    },
  // 修改用户和一键定位位置
  changeIcon: function () {
    const that = this;
    const { controls } = this.data;
    wx.getSystemInfo({
      success: function success(res) {
        var controlsH = res.windowWidth / 750 * 468;//计算一像素的宽度 res.windowWidth/750
        var map_height = res.windowHeight - controlsH;
        // console.log(res, '2222222222')
        controls[1] = {
          id: 2,
          iconPath: '../../../images/user/icon-30.png',
          position: {
            top: map_height - 56,
            left: 10,
            width: 50,
            height: 50
          },
          clickable: true
        };
        that.setData({
          winPath: {
            w: res.windowWidth,
            h: res.windowHeight
          },
          map_height,
          controls,
        });
      }
    });
  },
})